package com.eshop.web.controllers.web;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.eshop.common.constant.CoreConstant;
import com.eshop.common.constant.UserConstants;
import com.eshop.common.util.date.DateUtils;
import com.eshop.common.util.security.Base64;
import com.eshop.common.util.security.MD5;
import com.eshop.frameworks.core.controller.BaseController;
import com.eshop.frameworks.core.entity.EmailParam;
import com.eshop.frameworks.core.mail.MailSenderService;
import com.eshop.model.mongodb.EUser;
import com.eshop.service.mongodb.EUserService;
@Controller
public class FindPwdController extends BaseController{
	@Autowired
	private MailSenderService mailSenderService;
	@Autowired
	private EUserService euserService;
	
	@RequestMapping("/findPwd")
	public ModelAndView findPwd(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("/euser/findPwd.httl");
		setVar(mav);
		return mav;
	}

	@RequestMapping(value = "/reset", method = RequestMethod.POST)
	public ModelAndView reset(EUser euser, String key,
			HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("/message/reset_success.httl");
		setVar(mav);
		if (checkParam(key)||(key!=null&&!"".equals(euser.getMobile())&&key.endsWith(MD5.getMD5(euser.getMobile())))) {
			EUser user = euserService.findById(euser.getId(), EUser.class);
			user.setPassword(MD5.getMD5(euser.getPassword()));
			euserService.save(user);
		} else {
			mav.setViewName("/error/error_msg.httl");
			mav.addObject("msg", "无效连接");
			return mav;
		}
		return mav;
	}

	// 发送找回密码邮件
	@RequestMapping(value = "/sendResetPwdMail", method = RequestMethod.POST)
	public ModelAndView sendmail(EUser euser, HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("/message/send_pwd_success.httl");
		setVar(mav);
		EUser user = euserService.getByEmail(euser);
		try {
			if (user != null) {
				// 调取发送邮件接口
				String url = CoreConstant.contextPath + "/reset_pwd/"
						+ encrypt(user.getEmail());
				EmailParam ep = new EmailParam();
				ep.setEmail(user.getEmail());
				ep.setSubject("宅速乐找回密码邮件");
				ep.setActiveUrl(url);
				ep.setTemplateName(UserConstants.TEMPLATE_GET_PWD_EMAIL);
				ep.setToEmail(user.getEmail());
				Map<String, String> model = new HashMap<String, String>();
				model.put("nickName", user.getUsername());
				model.put("userName", user.getEmail());
				model.put("activeUrl", ep.getActiveUrl());
				model.put("adminEmail", UserConstants.ADMIN_EMAIL);
				model.put("nowdate",
						DateUtils.dateToStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
				model.put("img", CoreConstant.imagesPath);
				model.put("ctx", CoreConstant.contextPath);
				mailSenderService.sendWithTemplate(ep, model);
				user.setIsSendPwdMail(true);
				euserService.save(user);
				return mav;
			} else {
				mav.setViewName("/error/error_msg.httl");
				mav.addObject("msg", "邮箱输入错误");
				return mav;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mav;
	}
	
	
	

	// 验证找回密码key，并跳转到重设密码页面
	@RequestMapping(value = "/reset_pwd/{key}", method = RequestMethod.GET)
	public ModelAndView sendmail(@PathVariable(value = "key") String key,
			HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("/euser/reset_pwd.httl");
		setVar(mav);
		try {
			if (checkParam(key)) {
				String email = getNameFromP(key);
				EUser user = euserService.getByEmail(email);
				if (user.getIsSendPwdMail()) {
					user.setIsSendPwdMail(false);
					euserService.save(user);
					mav.addObject("user", user);
					mav.addObject("key", key);
				} else {
					mav.setViewName("/error/error_msg.httl");
					mav.addObject("msg", "无效连接");
					return mav;
				}
			} else {
				mav.setViewName("/error/error_msg.httl");
				mav.addObject("msg", "无效连接");
				return mav;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mav;
	}

	// 验证找回密码key，并跳转到重设密码页面
	@RequestMapping(value = "/mobileResetPwd", method = RequestMethod.POST)
	public ModelAndView mobilePwd(String mobile,String code, String key,
				HttpServletRequest request) {
			ModelAndView mav = new ModelAndView("/euser/reset_pwd.httl");
			setVar(mav);
			try {
				String scode = (String) this.getSessionAttribute(request, mobile + "_code");
				if (scode!=null&&key!=null&&scode.equals(code)&&key.equals(MD5.getMD5(mobile))) {
					EUser user = euserService.getByMobile(mobile);
					if(user==null){
						mav.setViewName("/error/error_msg.httl");
						mav.addObject("msg", "不存在此用户");
						return mav;
					}
					mav.addObject("user", user);
					mav.addObject("key", key);
				} else {
					mav.setViewName("/error/error_msg.httl");
					mav.addObject("msg", "验证码错误");
					return mav;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return mav;
		}
	
	private String encrypt(String name) {
		String str = name + ":||:" + System.currentTimeMillis();
		String md5 = MD5.getMD5(str + UserConstants.MD5_KEY);
		String result = null;
		try {
			result = Base64.encodeURL(str + ":||:" + md5);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return result;
	}

	private boolean checkParam(String p) {
		if (p == null)
			return false;
		String pStr = "";
		try {
			pStr = Base64.decodeURL(p);
		} catch (Exception e) {
			e.printStackTrace();
		}
		String[] arr = pStr.split(":\\|\\|:");
		return arr.length == 3
				&& (System.currentTimeMillis() - Long.parseLong(arr[1])) <= (60L * 1000 * 60 * 24 * 2)
				&& MD5.getMD5(arr[0] + ":||:" + arr[1] + UserConstants.MD5_KEY)
						.equals(arr[2]);

	}

	private String getNameFromP(String p) {
		String pStr = "";
		try {
			pStr = Base64.decodeURL(p);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return pStr.split(":\\|\\|:")[0];
	}

}
